﻿using System;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace AnycleLiu.Common.Security
{
    /// <summary>
    /// 对称加密帮助类
    /// 默认采用DES算法
    /// </summary>
    public class SymmetricCryptoHelper
    {
        private ICryptoTransform encryptor;
        private ICryptoTransform decryptor;
        private const int bufferSize = 1024;
        private byte[] iv = { 0x12, 0xab, 0x02, 0x90, 0xcf, 0xa1,0xee,0x1f };

        public SymmetricCryptoHelper(string algorithmName,byte[] key)
        {
            SymmetricAlgorithm symetricAlgorithm = SymmetricAlgorithm.Create(algorithmName);
            symetricAlgorithm.Key = key;
            symetricAlgorithm.IV = iv;

            encryptor = symetricAlgorithm.CreateEncryptor();
            decryptor = symetricAlgorithm.CreateDecryptor();
        }

        public SymmetricCryptoHelper(byte[] key):this("DES",key){}

        public byte[] Encrypt(byte[] clearBytes)
        {
            MemoryStream cleartexteam = new MemoryStream(clearBytes);
            MemoryStream ciphertexteam = new MemoryStream();
            CryptoStream cryptoStream = new CryptoStream(ciphertexteam, encryptor, CryptoStreamMode.Write);

            long readBytes=0;
            byte[] buffer = new byte[bufferSize];
            do
            {
                readBytes = cleartexteam.Read(buffer, 0, bufferSize);
                if (readBytes <= 0) break;
                cryptoStream.Write(buffer, 0, bufferSize);
            } while (true);

            cryptoStream.FlushFinalBlock();

            return ciphertexteam.ToArray();
        }

        public byte[] Decrypt(byte[] chiperBytes)
        {
            MemoryStream ciphertexteam = new MemoryStream(chiperBytes);
            MemoryStream cleartexteam = new MemoryStream();
            CryptoStream cryptoStream = new CryptoStream(ciphertexteam, decryptor, CryptoStreamMode.Read);

            long readBytes = 0;
            byte[] buffer = new byte[bufferSize];
            do
            {
                readBytes=cryptoStream.Read(buffer, 0, bufferSize);
                if (readBytes <= 0) break;
                cleartexteam.Write(buffer, 0, bufferSize);
            } while (true);

            cleartexteam.Flush();

            return cleartexteam.ToArray();
        }

        public string Encrypt(string cleartext)
        {
            byte[] dataBytes = Encoding.Default.GetBytes(cleartext);
            byte[] cipherBytes = Encrypt(dataBytes);

            return Convert.ToBase64String(cipherBytes);
        }

        public string Decrypt(string ciphertext)
        {
            byte[] dataBytes = Convert.FromBase64String(ciphertext);
            byte[] clearBytes = Decrypt(dataBytes);

            return Encoding.Default.GetString(clearBytes);
        }
    }
}
